/**
 *@Description 订单详情页
 *@Author zhangnf
 *@Date 2015-09-25
 */
var orderDetailCtrl  = new XFApp.client();
XFApp.client.prototype.orderDetail = {
	successCode : "10000",
	page : null,
	pageGoods : null,
	goodsSearchView : null,
	formValidateObj : null,
	urlItems : {
		getOrderByIdURL : basePath+"/userCenter/order/getOrderById",
		saveOrderURL : basePath+"/userCenter/order/saveOrder",
		queryByPageURL : basePath+"/userCenter/order/getDetailPage",
		delOrderURL : basePath+"/userCenter/order/delOrderDetail",
		saveGoodsURL : basePath+"/userCenter/order/saveOrderDetail",
		getGoodsURL : basePath+"/userCenter/order/getOrderDetailById",
		submitOrderURL : basePath+"/userCenter/order/submitOrder",
		applyURL : basePath+"/userCenter/bill/apply",
		queryGoodsByPageURL : basePath+"/userCenter/goods/goodsStats/queryPageByOrder",
		pushToTransOrderURL : basePath+"/userCenter/order/pushToTransOrder"
	},
	initData : function(orderId){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.getOrderByIdURL,
		    data:{  
		             id : orderId
		    },  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(data.code !=_this.successCode
		    			|| null == data.result){
	        		return;
	        	}
		    	var order = data.result;
		    	
		    	$("#editForm #detailTitle").text(_this.titleDisplay($("#typeId").val()));
		    	
		    	$("#editForm #orderCode").text(order.orderCode);
		    	$("#editForm #docketStatus").text(dksCtrl.dockerstatus.get(order.docketStatus));
		    	
		    	$("#editForm #customerCode").val(order.customerCode);
		    	$("#editForm #customerName").val(order.customerName);
		    	$("#editForm #ebpName").val(order.ebpName);
		    	$("#editForm #ebpCode").val(order.ebpCode);
		    	$("#editForm #orderNo").val(order.orderNo);
		    	$("#editForm #ebcName").val(order.ebcName);
		    	$("#editForm #agentName").val(order.agentName);
		    	$("#editForm #agentCode").val(order.agentCode);
		    	$("#editForm #goodsValue").val(order.goodsValue);
		    	$("#editForm #freight").val(order.freight);
		    	$("#editForm #cosignee").val(order.cosignee);
		    	$("#editForm #cosigneeAdd").val(order.cosigneeAdd);
		    	$("#editForm #cosigneeTel").val(order.cosigneeTel);
		    	$("#editForm #remark").val(order.remark);
		    	
		    	$("#editForm #orderTypeHidden").val(order.impExp);
		    	$("#editForm #currencyHidden").val(order.currency);
		    	$("#editForm #nationHidden").val(order.cosigneeCty);
		    	
		    	//进出口下拉框
		    	dictCtrl.dictionary.load("orderType","orderTypeHidden");
		    	//币制下拉框
		    	dictCtrl.dictionary.load("currency","currencyHidden");
		    	//国家下拉框
		    	dictCtrl.dictionary.load("nation","nationHidden");
		    	
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	titleDisplay : function(typeId){
		switch(typeId){
			case 0:return "查看";
			case 1:return "修改";
			case 2:return "新增";
			default : return "";
		}
	},
	formValidate : function(){
		$("#editForm").validate({
	        rules: {
	        	impExpValidate: "required",
	        	orderNo: "required",
	        	ebcName: "required",
	        	agentCode: "required",
	        	agentName: "required",
	        	goodsValue: {
	        		required: true,
	        		amount:true
	        	},
	        	freight: {
	        		required: true,
	        		amount:true
	        	},
	        	cosignee: "required",
	        	cosigneeAdd: "required",
	        	cosigneeTel: "required",
	        	currencyValidate: "required",
	        	nationValidate: "required"
			  },
			 messages: {
				impExpValidate: "请选择订单类型",
	        	orderNo: "请填写订单编号",
	        	ebcName: "请填写申报企业名称",
	        	agentCode: "请填写申报企业代码",
	        	agentName: "请填写申报企业名称",
	        	goodsValue: {
	        		required: "请填写订单商品货款"
	        	},
	        	freight: {
	        		required: "请填写订单商品运费"
	        	},
	        	cosignee: "请填写收货人名称",
	        	cosigneeAdd: "请填写收货人地址",
	        	cosigneeTel: "请填写收货人电话",
	        	currencyValidate: "请选择币制",
	        	nationValidate: "请选择收货人所在国"
			  }
	    });
		formValidateObj = $("#editForm").validate();
	},
	saveForm : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.saveOrderURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	_this.refreshOrderId(data.result);
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {  
		    	window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	saveFormStatic : function(id,typeId){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.saveOrderURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	_this.refreshOrderId(data.result);
		    	_this.detailOrderView(id,typeId);
		     },  
		     error : function() {  
		    	window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	submitForm : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.submitOrderURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	_this.refreshOrderId(data.result);
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	applyForm : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.applyURL,
		    data:$('#editForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	_this.refreshOrderId(data.result);
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	pushToTransOrder : function(){
		_this = this;
		$.ajax( {  
		    url:_this.urlItems.pushToTransOrderURL,
		    data:{id:$("#editForm #orderId").val()},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		    	if(data.isSuccess){
		    		_this.refreshOrderId(data.result);
		    	}
		     },  
		     error : function() {  
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	detailPage : function(){
		_this = this;
		var params = $("#editGoodsForm").serialize();
		if(!!_this.page){
			_this.page.page("remote",0,params);
		}else{
			_this.page = $("#page").page({
				pageSize : 10,
				remote: {
					url: _this.urlItems.queryByPageURL,
			        params: params,
			        success: function (data, pageIndex) {
			        	if(data.isSuccess == true){
			        		var pageResult = data.result;
			        		if(null == data 
									|| null == data.result 
										|| null == data.result.itemList
											|| data.result.itemList.length < 1){
			        			$("#page_grid").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        		}else{
			        			$("#page_grid").html($("#dataTmp").render(pageResult.itemList));
			        		}
			        	}else{
			        		window.webDialogUtil.alert("提示","操作失败");
			        	}
			        	$("#editGoodsForm #sortNo").val(data.result.totalRecord);
			        },
			        error : function(){
			        	window.webDialogUtil.alert("提示","操作失败");
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页,{total}项'
			});
		}
	},
	delOrderDialog : function(id,itemName){
		_this = this;
		webAlert({
            title:'提示',
            content:'确定要删除 '+itemName+' 吗?',
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.delOrder(id);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	delOrder : function(id){
		_this = this;
		$.ajax({
		    url:_this.urlItems.delOrderURL,
		    data:{id:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(true == data.isSuccess){
		    		_this.detailPage();
		    		$("#goodsValue").val(data.result);
		    	}
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	detailOrderView : function(id,typeId){
		_this = this;
//		if("" == $("#orderId").val()){
//			window.webDialogUtil.alert("提示","请先保存基本信息");
//    		return;
//		}
		
		if(null == id){
			//币制下拉框
	    	dictCtrl.dictionary.load("currency","editGoodsForm #currencyHidden","editGoodsForm #currency");
	    	//计量单位下拉框
	    	dictCtrl.dictionary.load("measureUnit","editGoodsForm #unitHidden","editGoodsForm #unit");
			return this.detailOrderDialog(null,typeId);
		}
		$.ajax({
		    url:_this.urlItems.getGoodsURL,
		    data:{detailId:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(false == data.isSuccess){
		    		window.webDialogUtil.alert("提示","获取数据失败");
		    		return;
		    	}
		    	_this.detailOrderDialog(data.result,typeId);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	detailOrderDialog : function(data,typeId){
		var sortNo = $("#editGoodsForm #sortNo").val();
		if(null != data){
			$("#editGoodsForm #detailId").val(data.id);
			$("#editGoodsForm #itemNo").val(data.itemNo);
	    	$("#editGoodsForm #goodsCode").val(data.goodsCode);
	    	$("#editGoodsForm #gNo").val(data.gNo);
	    	$("#editGoodsForm #gCode").val(data.gCode);
	    	$("#editGoodsForm #gName").val(data.gName);
	    	$("#editGoodsForm #itemName").val(data.itemName);
	    	$("#editGoodsForm #gModel").val(data.gModel);
	    	$("#editGoodsForm #barCode").val(data.barCode);
	    	$("#editGoodsForm #brand").val(data.brand);
	    	$("#editGoodsForm #updateTime").text(this.dataFormat(data.updateTime));
	    	$("#editGoodsForm #updatePerson").text(data.updatePerson);
	    	
	    	$("#editGoodsForm #qty").val(data.qty);
	    	$("#editGoodsForm #price").val(data.price);
	    	$("#editGoodsForm #total").val(data.total);
	    	$("#editGoodsForm #remark").val(data.remark);
	    	
	    	$("#editGoodsForm #unitHidden").val(data.unit);
	    	$("#editGoodsForm #currencyHidden").val(data.currency);
		}else{
			$("#editGoodsForm #itemNo").text("");
	    	$("#editGoodsForm #goodsCode").text("");
	    	$("#editGoodsForm #gNo").text("");
	    	$("#editGoodsForm #gCode").text("");
	    	$("#editGoodsForm #gName").text("");
	    	$("#editGoodsForm #itemName").text("");
	    	$("#editGoodsForm #gModel").text("");
	    	$("#editGoodsForm #barCode").text("");
	    	$("#editGoodsForm #brand").text("");
	    	$("#editGoodsForm #brand").text("");
	    	$("#editGoodsForm #updateTime").text("");
	    	$("#editGoodsForm #updatePerson").text("");
	    	
			$("#editGoodsForm")[0].reset();
			$("#editGoodsForm #sortNo").val(sortNo);
		}
		$("#editGoodsForm #orderId").val($("#editForm #orderId").val());
		//币制下拉框
    	dictCtrl.dictionary.load("currency","editGoodsForm #currencyHidden","editGoodsForm #currency");
    	//计量单位下拉框
    	dictCtrl.dictionary.load("measureUnit","editGoodsForm #unitHidden","editGoodsForm #unit");
		webAlert({
            title:orderDetailCtrl.orderDetail.titleDisplay(typeId),
            content:document.getElementById("goodsView"),
            button:[
					{
					name:"暂存",
					callback:function(){
						if($("#editGoodsForm").validate().form()){
							orderDetailCtrl.orderDetail.saveGoodsForm();
						}else{
							return false;
						}
					}},
                    {
                    name:"关闭",
                    callback:function(){
                  	  this.close();
                    }
                   }]
            });
	},
	goodsFormValidate : function(){
		$("#editGoodsForm").validate({
	        rules: {
	        	qty: {
	        		required: true,
	        		positiveInteger:true
	        	},
	        	price: {
	        		required: true,
	        		amount:true
	        	},
	        	total: "amount",
	        	itemNo: "required"
			  },
			 messages: {
				qty: {
	        		required: "请填写成交数量"
				},
				price: {
	        		required: "请填写单价"
				},
				itemNo: "请填选择企业商品货号"
			  }
	    });
		$("#editGoodsForm").validate();
	},
	saveGoodsForm : function(){
		_this = this;
		$.ajax( {
		    url:_this.urlItems.saveGoodsURL,
		    data:$('#editGoodsForm').serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(true == data.isSuccess){
		    		_this.detailPage();
		    		$("#goodsValue").val(data.result);
		    	}
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	openGoodsSearch : function(isOpen){
		_this = this;
		var params = $("#searchFormGoods").serialize();
		if(!!_this.pageGoods){
			_this.pageGoods.page("remote",0,params);
		}else{
			_this.pageGoods = $("#pageGoods").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryGoodsByPageURL,
			        params: params,
			        success: function (data, pageIndex) {
			        	if(data.isSuccess == true){
			        		var pageResult = data.result;
			        		if(null == data 
									|| null == data.result 
										|| null == data.result.itemList
											|| data.result.itemList.length < 1){
			        			$("#page_grid_goods").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        		}else{
			        			$("#page_grid_goods").html($("#dataTmpGoods").render(pageResult.itemList));
			        		}
			        	}else{
			        		window.webDialogUtil.alert("提示","操作失败");
			        	}
			        },
			        error : function(){
			        	window.webDialogUtil.alert("提示","操作失败");
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页,{total}项'
			});
		}
	},
	openGoodsSearchView : function(){
		var _this = this;
		this.goodsSearchView = webAlert({
            title:"选择商品",
            content:document.getElementById("goodsSearchView")
            });
		$("#searchFormGoods")[0].reset();
		this.openGoodsSearch();
	},
	toEditGoodsForm : function(itemNo,goodsCode,gNo,gCode,gName,itemName,gModel,barCode,brand){
		$("#editGoodsForm #itemNo").val(itemNo);
		$("#editGoodsForm #goodsCode").val(goodsCode);
		$("#editGoodsForm #gNo").val(gNo);
		$("#editGoodsForm #gCode").val(gCode);
		$("#editGoodsForm #gName").val(gName);
		$("#editGoodsForm #itemName").val(itemName);
		$("#editGoodsForm #gModel").val(gModel);
		$("#editGoodsForm #barCode").val(barCode);
		$("#editGoodsForm #brand").val(brand);
		this.goodsSearchView.close();
	},
	dataFormat : function(timeLong){
		if(null == timeLong
				|| "" == timeLong){
			return "";
		}
		return new Date(timeLong*1000).format("yyyy-MM-dd hh:mm:ss")
	},
	refreshOrderId : function(order){
		if(null == order){
			return;
		}
		$("#editGoodsForm #orderId").val(order.id);
		$("#editForm #orderId").val(order.id);
		$("#editForm #orderCode").text(order.orderCode);
		$("#editForm #docketStatus").text(dksCtrl.dockerstatus.get(order.docketStatus));
	},
	calcTotal : function(){
		var price = $("#editGoodsForm #price").val();
		var qty = $("#editGoodsForm #qty").val();
		if(price > 0 && qty > 0){
			$("#editGoodsForm #total").val(price*qty);
		}else{
			$("#editGoodsForm #total").val("");
		}
	},
	event : function(){
		_this = this;
		
		$("#submitBtn").on("click",function(){
			//订单表单验证
			orderDetailCtrl.orderDetail.formValidate();
			if($("#editForm").validate().form()){
				orderDetailCtrl.orderDetail.submitForm();
			}
		});
		
		$("#applyBtn").on("click",function(){
			if($("#editForm").validate().form()){
				orderDetailCtrl.orderDetail.applyForm();
			}
		});
		
		$("#saveBtn").on("click",function(){
			//订单表单取消验证
			if(!(typeof(formValidateObj)=="undefined")){
				formValidateObj.resetForm();
			}
			orderDetailCtrl.orderDetail.saveForm();
		});
		$("#itemNoBtn").on("click",function(){
			orderDetailCtrl.orderDetail.openGoodsSearchView();
		});
		$("#goodsSearchBtn").on("click",function(){
			orderDetailCtrl.orderDetail.openGoodsSearch();
		});
		$("#pushToTransOrderBtn").on("click",function(){
			orderDetailCtrl.orderDetail.pushToTransOrder();
		});
		$("#editGoodsForm #price").on("input",function(){
			orderDetailCtrl.orderDetail.calcTotal();
		});
		$("#editGoodsForm #qty").on("input",function(){
			orderDetailCtrl.orderDetail.calcTotal();
		});
		
		//商品表单验证
		this.goodsFormValidate();
		//详情分页
    	_this.detailPage();
	},
};
$.views.converters({
	ftime : function(value) {
		return orderDetailCtrl.orderDetail.dataFormat(value) ;
	},
	fdkstatus : function(value){
		return dksCtrl.dockerstatus.get(value);
	},
	fmoney : function(value){
		if(null == value
				|| "" == value){
			return "";
		}
		return orderDetailCtrl.fmoney(value);
	}
});
$.views.helpers({
    "checkStatus": function(status){
    	return $("#editForm #docketStatusHid").val()==status?true:false;
    }
});
$(function(){
	//初始化编辑数据
	var orderId = $("#orderId").val();
	if(null != orderId && orderId > 0){
		orderDetailCtrl.orderDetail.initData(orderId);
	}else{
		//进出口下拉框
    	dictCtrl.dictionary.load("orderType","orderTypeHidden");
    	//币制下拉框
    	dictCtrl.dictionary.load("currency","currencyHidden");
    	//国家下拉框
    	dictCtrl.dictionary.load("nation","nationHidden");
	}
	
	//初始化事件
	orderDetailCtrl.orderDetail.event();
});